import math
from queue import Queue
heap = ['o',7,19,18,27,53,30,51,48,48,60]
d = Queue([12])

n = len(heap)
def bulid(index,limit):
    # 递归所有孩子
    if index >= limit: return False
    if index ==1: return True
    if heap[index] > heap[index//2]:
        heap[index],heap[index//2] = heap[index//2],heap[index]
        bulid(2*index+1,limit)
        bulid(2*index,limit)

    
def print_tree(tree):
    deepth = int(math.log2(n)) +1
    level = 0
    status = 0  # 设置打印左还是右
    while level < deepth:
        space = ' '*2**(deepth - level)

        for i in range(2**level,min(2**(level+1),n)):
            if i == 1: continue
            print(space,"/\\"[status],end=space)
            status = (status +1) %2
        print()
        for i in range(2**level,min(2**(level+1),n)):
            print(space,tree[i],end=space)
        level += 1
        print()



for i in range(n,-1,-1):  # 建大根堆
    if bulid(i,n):
        break

print(heap)
print_tree(heap)

# 将根节点放在最后再建堆
for i in range(n-1,0,-1):
    heap[1],heap[i] = heap[i],heap[1]
    for j in range(i-1,0,-1):
        if bulid(j,i):
            break

print_tree(heap)
print(heap)